export default {
  // 开启命名空间
  namespaced: true,
  // 数据存储位置
  state: function() {
    return {
      // 共享数据
      // 每个商品的信息对象，都包含如下 6 个属性：
      // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
      cart: JSON.parse(uni.getStorageSync('cart') || '[]')
    }
  },
  mutations: {
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 修改state上的数据 只能在mutations定义相关方法完成数据修改
    addToCart(state, goods) {
      let findResult = state.cart.find(function(item) {
        return item.goods_id == goods.goods_id;
      })
      // console.log('findResult',findResult);  
      if (!findResult) {
        state.cart.push(goods);
      } else {
        findResult.goods_count++;
      }
      // console.log('cart',state.cart);
      this.commit('m_cart/saveToStorage');
    },
    // 更新商品选中状态
    updateGoodState(state, goods_id) {
      // 根据商品id查找当前商品
      let findResult = state.cart.find(x => x.goods_id === goods_id);
      if (findResult) {
        findResult.goods_state = !findResult.goods_state
        this.commit('m_cart/saveToStorage');
      }
    },
    // 修改商品数量
    updateGoodCount(state, goods) {
      let findResult = state.cart.find(x => x.goods_id == goods.goods_id);
      if (findResult) {
        findResult.goods_count = goods.goods_count;
        this.commit('m_cart/saveToStorage');
      }

    },
    // 根据商品id删除商品
    removeGoodById(state, goods) {
      state.cart = state.cart.filter(function(item) {
        return item.goods_id !== goods.goods_id
      });
      this.commit('m_cart/saveToStorage');
    },
    // 点击全选 设置所有商品的选中状态
    updateAllGoodsState (state, newState) {
        state.cart.forEach(x=>x.goods_state = newState);
        this.commit('m_cart/saveToStorage');
    }
  },
  // 数据包装器
  getters: {
    total(state) {
      let sum = 0;
      state.cart.forEach(function(item) {
        sum += item.goods_count;
      });
      return sum;
    },
    // 已选商品总数量
    checkedCount(state) {
      // 已选中的商品
      return state.cart.filter((item) => item.goods_state)
                       .reduce((total, item) => total += item.goods_count, 0)
    },
    checkedGoodsAmount (state) {
       return state.cart.filter(x=>x.goods_state)
                        .reduce((total,item)=>total += item.goods_price * item.goods_count ,0)
                        .toFixed(2)
    }
  }
}
